﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using KVB.Common;
using Customer_Profile.eCard.DBDao;
using Customer_Profile.Admin;
using System.Data.SqlClient;

namespace Customer_Profile.eCard.Reward
{
    public partial class application_pay_detail : System.Web.UI.Page
    {
        int str_id ;
        string strUserName = "";
        string strUserID = "";
        string strEntity = "";
        public string strScript = "";
        protected void Page_Load(object sender, EventArgs e)
        {
            Comm.CheckSession(this.Page, "/login.aspx", "usermodel");
            if (Session["usermodel"] != null)
            {
                strUserID = ((UserInfoEntity)Session["usermodel"]).UserLoginId;
                strUserName = ((UserInfoEntity)Session["usermodel"]).UserName;
                strEntity = ((UserInfoEntity)Session["usermodel"]).UserOffice;
            }
            else
            {
                Log.WriteDefaultLog("main_01 Page_Load", "Session is null");
                return;
            }

            if (Request["reward_batch_id"] != null)
            {
                str_id = int.Parse(Request["reward_batch_id"].ToString());
            }
            else
            {
                return;
            }
            //dsAgent = SaleAgentDao.getSettleAgentList("Y");
            //dsPaymethod = Comm.getTypeList("SettlePayMethod");

            if (!Page.IsPostBack)
            {
                bindSubGrid(str_id);
                getPaySumAmount(str_id);
                bindRewardAccountInfo(str_id);
            }
        }

        private void getPaySumAmount(int str_id)
        {
            try
            {
                DataSet ds = null;
                ds = RewardDao.RewardPaySumAmount(str_id);
                txtActualSumAmount.Text = ds.Tables[0].Rows[0]["total_amount"].ToString();
            }
            catch (Exception ex)
            {
                lblWarning.Text = ex.ToString();
            }
        }

        private void bindRewardAccountInfo(int str_id)
        {
            try
            {
                DataSet ds = null;
                ds = RewardDao.RewardAccountInfo(str_id);
                txtYear.Text = ds.Tables[0].Rows[0]["year"].ToString();
                txtMonth.Text = ds.Tables[0].Rows[0]["month"].ToString();
                account_name.Text = ds.Tables[0].Rows[0]["account_name"].ToString();
                staff_no.Text = ds.Tables[0].Rows[0]["staff_no"].ToString();
                reward_bankaccount.Text = ds.Tables[0].Rows[0]["reward_bankaccount"].ToString();
                txtRemark.Text = ds.Tables[0].Rows[0]["remark"].ToString();
            }
            catch (Exception ex)
            {
                lblWarning.Text = ex.ToString();
            }
        }

        private void bindSubGrid(int str_id)
        {
            try
            {
                DataSet ds = null;
                ds = RewardDao.RewardPayDetailByBatchID(str_id);
                rpt.DataSource = ds;
                rpt.DataBind();
            }
            catch (Exception ex)
            {
                lblWarning.Text = ex.ToString();
            }
        }

        protected void btnConfirm_Click(object sender, EventArgs e)
        {  
            SqlConnection conn = null;
            DB.Connection(ref conn);
            SqlTransaction trans = conn.BeginTransaction();
            SqlCommand sqlCommand = new SqlCommand();
            sqlCommand.Connection = conn;
            sqlCommand.Transaction = trans;

            try
            {
                foreach (RepeaterItem ri in this.rpt.Items)
                {
                    if (ri.ItemType != ListItemType.Header && ri.ItemType != ListItemType.Footer)
                    {
                        Label lblRewardID = ri.FindControl("lblRewardID") as Label;
                        TextBox txtActualAmount = ri.FindControl("txtActual_amount") as TextBox;
                        TextBox txtSpreadActualamount = ri.FindControl("txtSpreadActual_amount") as TextBox;
                        TextBox txtRemark = ri.FindControl("txtRemark") as TextBox;
                        sqlCommand.Parameters.Clear();
                        int iReward_ID = int.Parse(lblRewardID.Text.Trim());
                        decimal dActualAmount = decimal.Parse(txtActualAmount.Text.Trim());
                        decimal dSpreadActualAmount = decimal.Parse(txtSpreadActualamount.Text.Trim());
                        string sRemark = txtRemark.Text.Trim();

                        sqlCommand.Parameters.Add("@reward_id", SqlDbType.Int);
                        sqlCommand.Parameters.Add("@actual_amount", SqlDbType.Decimal);
                        sqlCommand.Parameters.Add("@spread_actual_amount", SqlDbType.Decimal);
                        sqlCommand.Parameters.Add("@remark", SqlDbType.VarChar, 250);

                        sqlCommand.Parameters["@reward_id"].Value = iReward_ID;
                        sqlCommand.Parameters["@actual_amount"].Value = dActualAmount;
                        sqlCommand.Parameters["@spread_actual_amount"].Value = dSpreadActualAmount;
                        sqlCommand.Parameters["@remark"].Value = sRemark;

                        sqlCommand.CommandType = CommandType.StoredProcedure;
                        sqlCommand.CommandText = "eCard_Reward_PayConfirm";
                        sqlCommand.ExecuteNonQuery();

                    }
                }
                decimal dSumActualAmount =decimal.Parse(txtActualSumAmount.Text);
                
                sqlCommand.Parameters.Clear();
                sqlCommand.Parameters.Add("@batch_id", SqlDbType.Int);
                sqlCommand.Parameters.Add("@actual_amount", SqlDbType.Decimal);
                sqlCommand.Parameters.Add("@userid", SqlDbType.VarChar,50);
                sqlCommand.Parameters.Add("@username", SqlDbType.VarChar,50);


                sqlCommand.Parameters["@batch_id"].Value = str_id;
                sqlCommand.Parameters["@actual_amount"].Value = dSumActualAmount;
                sqlCommand.Parameters["@actual_amount"].Precision = (byte)18;
                sqlCommand.Parameters["@actual_amount"].Scale = (byte)2;

                sqlCommand.Parameters["@userid"].Value = strUserID;
                sqlCommand.Parameters["@username"].Value = strUserName;

                sqlCommand.CommandType = CommandType.StoredProcedure;
                sqlCommand.CommandText = "eCard_reward_pay";
                sqlCommand.ExecuteNonQuery();
                trans.Commit();
                //lblWarning.Text = "";
                strScript = "<script>alert('更新成功！'); window.opener.refresh();window.opener=null; window.open('', '_self');window.close();</script>";                
            }
            catch (Exception ex)
            {
                lblWarning.Text = "更新失败";
                KVB.Common.Log.WriteDefaultLog("application_pay_detail.btnConfirm_Click", ex.ToString());
                trans.Rollback();
                Response.Write("<script>alert('更新失败！'+" + ex.ToString() + ");</script>");
            }
            finally
            {
                DB.ConnDispose(ref conn);
                trans.Dispose();
                conn.Dispose();
            }
        }

        protected void btnReview_Click(object sender, EventArgs e)
        {
            SqlConnection conn = null;
            DB.Connection(ref conn);
            SqlTransaction trans = conn.BeginTransaction();
            SqlCommand sqlCommand = new SqlCommand();
            sqlCommand.Connection = conn;
            sqlCommand.Transaction = trans;

            try
            {
                foreach (RepeaterItem ri in this.rpt.Items)
                {
                    if (ri.ItemType != ListItemType.Header && ri.ItemType != ListItemType.Footer)
                    {
                        Label lblRewardID = ri.FindControl("lblRewardID") as Label;
                        TextBox txtActualAmount = ri.FindControl("txtActual_amount") as TextBox;
                        TextBox txtSpreadActualamount = ri.FindControl("txtSpreadActual_amount") as TextBox;
                        TextBox txtRemark = ri.FindControl("txtRemark") as TextBox;
                        sqlCommand.Parameters.Clear();
                        int iReward_ID = int.Parse(lblRewardID.Text.Trim());
                        decimal dActualAmount = decimal.Parse(txtActualAmount.Text.Trim());
                        decimal dSpreadActualAmount = decimal.Parse(txtSpreadActualamount.Text.Trim());
                        string sRemark = txtRemark.Text.Trim();

                        sqlCommand.Parameters.Add("@reward_id", SqlDbType.Int);
                        sqlCommand.Parameters.Add("@actual_amount", SqlDbType.Decimal);
                        sqlCommand.Parameters.Add("@spread_actual_amount", SqlDbType.Decimal);
                        sqlCommand.Parameters.Add("@remark", SqlDbType.VarChar, 250);

                        sqlCommand.Parameters["@reward_id"].Value = iReward_ID;
                        sqlCommand.Parameters["@actual_amount"].Value = dActualAmount;
                        sqlCommand.Parameters["@spread_actual_amount"].Value = dSpreadActualAmount;
                        sqlCommand.Parameters["@remark"].Value = sRemark;

                        sqlCommand.CommandType = CommandType.StoredProcedure;
                        sqlCommand.CommandText = "eCard_Reward_PayConfirm";
                        sqlCommand.ExecuteNonQuery();

                    }
                }
                decimal dSumActualAmount = decimal.Parse(txtActualSumAmount.Text);

                sqlCommand.Parameters.Clear();
                sqlCommand.Parameters.Add("@batch_id", SqlDbType.Int);
                sqlCommand.Parameters.Add("@actual_amount", SqlDbType.Decimal);
                sqlCommand.Parameters.Add("@userid", SqlDbType.VarChar, 50);
                sqlCommand.Parameters.Add("@username", SqlDbType.VarChar, 50);


                sqlCommand.Parameters["@batch_id"].Value = str_id;
                sqlCommand.Parameters["@actual_amount"].Value = dSumActualAmount;
                sqlCommand.Parameters["@actual_amount"].Precision = (byte)18;
                sqlCommand.Parameters["@actual_amount"].Scale = (byte)2;

                sqlCommand.Parameters["@userid"].Value = strUserID;
                sqlCommand.Parameters["@username"].Value = strUserName;

                sqlCommand.CommandType = CommandType.StoredProcedure;
                sqlCommand.CommandText = "eCard_reward_Review";
                sqlCommand.ExecuteNonQuery();
                trans.Commit();
                lblWarning.Text = "奖励审核成功";                
            }
            catch (Exception ex)
            {
                lblWarning.Text = "奖励审核失败";
                KVB.Common.Log.WriteDefaultLog("application_pay_detail.btnReview_Click", ex.ToString());
                trans.Rollback();
                Response.Write("<script>alert('奖励审核失败！'+" + ex.ToString() + ");</script>");
            }
            finally
            {
                DB.ConnDispose(ref conn);
                trans.Dispose();
                conn.Dispose();
            }
        }

        protected void btnUpdateAccountNo_Click(object sender, EventArgs e)
        {
            try
            {
                string year = txtYear.Text.Trim();
                string month = txtMonth.Text.Trim();
                string str_account_name = account_name.Text.Trim();

                string str_staff_no = staff_no.Text.Trim();
                string str_reward_bankaccount = reward_bankaccount.Text.Trim();
                string remark = txtRemark.Text.Trim();

                RewardDao.RewardUpbdateAccountInfoByBatchID(str_id, year, month, str_account_name, str_staff_no, str_reward_bankaccount, remark);
                lblWarning.Text = "奖励批次信息修改成功！";
            }
            catch (Exception ex)
            {
                lblWarning.Text = ex.ToString();
            }
        }
    }
}